package the.broccoli.et.application.service;

import com.github.pagehelper.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.wisteria.framework.web.QueryResult;
import the.broccoli.et.domain.model.UserEventStatistic;
import the.broccoli.et.domain.repository.EventTriggerRepository;
import the.broccoli.et.infrastructure.persistent.model.EventTrigger;
import the.broccoli.et.interfaces.dto.EventTriggerCondition;
import the.broccoli.et.interfaces.dto.EventTriggerDTO;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lei.liu
 * @date 2021/7/20
 */
@Service
public class EventTriggerService {

    @Resource
    private EventTriggerRepository eventTriggerRepository;

    public boolean saveEventTrigger(EventTrigger eventTrigger) {
        return eventTriggerRepository.save(eventTrigger) > 0;
    }

    /**
     * 分页查询
     * @param condition 查询条件
     * @return
     */
    public QueryResult<EventTriggerDTO> pageList(EventTriggerCondition condition) {
        Page<EventTrigger> page = eventTriggerRepository.selectListPage(condition);
        QueryResult queryResult = new QueryResult();
        if (!CollectionUtils.isEmpty(page.getResult())) {
            List<EventTriggerDTO> dataList = page.getResult().stream().map(this::toEventTriggerDTO).collect(Collectors.toList());
            queryResult.setItems(dataList);
        }
        queryResult.setTotal(page.getTotal());
        return queryResult;
    }

    public List<UserEventStatistic> listUserEventStatistic(String eventCode, LocalDateTime start, LocalDateTime end) {
        return eventTriggerRepository.listUserEventStatistic(eventCode, start, end);
    }

    private EventTriggerDTO toEventTriggerDTO(EventTrigger eventTrigger) {
        EventTriggerDTO dto = new EventTriggerDTO();
        BeanUtils.copyProperties(eventTrigger, dto);
        return dto;
    }

}
